/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.jdesktop.wonderland.modules.printscreenplugin.client;

import java.awt.Canvas;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.jdesktop.wonderland.client.jme.JmeClientMain;
import org.jdesktop.wonderland.client.login.ServerSessionManager;
import org.jdesktop.wonderland.modules.contentrepo.client.ContentRepository;
import org.jdesktop.wonderland.modules.contentrepo.client.ContentRepositoryRegistry;
import org.jdesktop.wonderland.modules.contentrepo.common.ContentCollection;
import org.jdesktop.wonderland.modules.contentrepo.common.ContentNode;
import org.jdesktop.wonderland.modules.contentrepo.common.ContentRepositoryException;
import org.jdesktop.wonderland.modules.contentrepo.common.ContentResource;

/**
 *
 * @author Dominik
 */
public class TakePrintScreen {
    
    private boolean localSave; 
    private String filePathLocal;
    private int screenShotNumber = 0;
    private ContentRepository repo;
    private ServerSessionManager serverSession;
    private String webDavFolder;
    private String screenShotFolder;
    private String screenShotName;
    private static final Logger LOGGER =
            Logger.getLogger(JmeClientMain.class.getName());
    
    public TakePrintScreen(ServerSessionManager ss)
    {
        serverSession = ss;
        repo = ContentRepositoryRegistry.getInstance().getRepository(serverSession);
        webDavFolder = "images";
        screenShotFolder = "screenshot";
        
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-kk-mm-ss");
        
        screenShotName = sdf.format(cal.getTime()) + "_hslu_campus_";
        
        LOGGER.log(Level.INFO, webDavFolder + "/" + screenShotName);
    }
    
    
    private void savePrintScreenToWebDav(BufferedImage screenshot) throws ContentRepositoryException, IOException
    {
        int itemCount = 0;
        int lineCount = 0;
        String line;
        String gestureName = "";
        DataInputStream in = null;

        // TODO I'm defaulting this to 12 here for now as it meets my current need but I need to cater for variable lengths in the future
        ArrayList<double[]> frames = new ArrayList<double[]>();
        double[] items = new double[20];
        
        FileInputStream fstream = null;
        InputStream istream = null;
        BufferedReader br = null;
        
        //For reading from Repo
        ContentResource current = null;
        ContentCollection ccr = null;
        String strLine;

        ccr = repo.getRoot();
        //istream = this.getClass().getResourceAsStream(fileLocation);
        ContentNode node = null;
        node = ccr.getChild(webDavFolder + "/" + screenShotFolder);
        
        if(node == null)
        {
            ccr = (ContentCollection) ccr.getChild(webDavFolder);
            node = ccr.createChild(screenShotFolder, ContentNode.Type.COLLECTION);
        }
        
        ccr = repo.getRoot();
        
        ccr = (ContentCollection) ccr.getChild(webDavFolder + "/" + screenShotFolder);
        current = (ContentResource) ccr.createChild(screenShotName + screenShotNumber + ".png", ContentNode.Type.RESOURCE);
        
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(screenshot, "png", baos);
        InputStream is = new ByteArrayInputStream(baos.toByteArray());
        
        current.put(is);
    }
    
    private void savePrintScreenToClient(BufferedImage screenshot) throws IOException
    {   
        
        ImageIO.write(screenshot,"png", new File(filePathLocal + File.separator + screenShotName + screenShotNumber + ".png"));
    }

    public boolean takeScreenshot()
    {
        boolean retVal = true;
        
        JFrame saveFrame = JmeClientMain.getFrame().getFrame();
        JPanel savePanel = JmeClientMain.getFrame().getCanvas3DPanel();
        Canvas saveCan = JmeClientMain.getFrame().getCanvas(); 
        try {
            BufferedImage screenshot = new Robot().createScreenCapture(new Rectangle(saveFrame.getX()+8, saveFrame.getY()+85, saveCan.getWidth(), saveCan.getHeight()));
            
            if(isLocalSave())
            {
                savePrintScreenToClient(screenshot);
            }
            else
            {
                savePrintScreenToWebDav(screenshot);
            }
            
            screenShotNumber++;
        } catch (Exception ex)
        {
            ex.printStackTrace();
            retVal = false;
        }
        
        return retVal;
    }
    
    /**
     * @return the localSave
     */
    public boolean isLocalSave() {
        return localSave;
    }

    /**
     * @param localSave the localSave to set
     */
    public void setLocalSave(boolean localSave) {
        this.localSave = localSave;
    }

    /**
     * @param filePathLocal the filePathLocal to set
     */
    public void setFilePathLocal(String filePathLocal) {
        this.filePathLocal = filePathLocal;
    }

}
